Deep copy
function itemCopy(item) {
// Check if item is null or not an object; if so, return it as is (base case for recursion)
if (item === null || typeof item !== "object") {
return item;
}
// Check if item is an array, perform a deep copy of the array
if (Array.isArray(item)) {
let arr = [];
// Iterate over all elements of the array and recursively copy them
for (let [index, value] of item.entries()) {
arr[index] = itemCopy(value);
}
return arr; // Return the new array
}
// Check if item is an object, perform a deep copy of the object
if (item instanceof Object) {
let obj = {};
// Iterate over all properties of the object and recursively copy them
for (let [key, value] of Object.entries(item)) {
obj[key] = itemCopy(value);
}
return obj; // Return the new object
}
}
function createDeepCopy(...items) {
const finalCopy = [];
// Iterate over all provided items and add their deep copies to finalCopy
for (let i = 0; i < items.length; i++) {
finalCopy.push(itemCopy(items[i]));
}
return finalCopy; // Return the array with deep copies of the items
}
console.log(createDeepCopy([2, 10, 14, 100], { 1: "value" }, 1));